import { Input } from 'antd';
import React, { useEffect, useState } from 'react';

import captchaService from '@/api/services/security/captchaService';

import styles from './css/Captcha.module.css';

export interface CaptchaActionType {
  reset: () => void;
}

interface CaptchaProps {
  onCaptchaChange?: (captcha: string, uuid: string) => void;
  placeholder?: string;
  // 【新增】：接收一个 Ref 对象，用于向上传递方法
  actionRef?: React.MutableRefObject<CaptchaActionType | null>;
}

// eslint-disable-next-line react/function-component-definition
const Captcha: React.FC<CaptchaProps> = ({
  onCaptchaChange,
  placeholder = '请输入验证码',
  actionRef,
}) => {
  const [captchaImage, setCaptchaImage] = useState<string>('');
  const [captchaUuid, setCaptchaUuid] = useState<string>('');
  const [inputCode, setInputCode] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>('');

  // 获取验证码
  const fetchCaptcha = async () => {
    try {
      setLoading(true);
      setError('');
      const response = await captchaService.captcha();
      if (response) {
        setCaptchaImage(response.base64);
        setCaptchaUuid(response.uuid);
      }
    } catch (err) {
      setError('获取验证码失败，请重试');
      console.error('Captcha fetch failed:', err);
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载验证码
  useEffect(() => {
    fetchCaptcha();
  }, []);

  // 输入变化处理
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value.replace(/[^a-zA-Z0-9]/g, '');
    setInputCode(value);
    if (onCaptchaChange) {
      onCaptchaChange(value, captchaUuid);
    }
  };

  // 【新增】：将 reset 方法挂载到 actionRef 上
  useEffect(() => {
    if (actionRef) {
      actionRef.current = {
        reset: () => {
          setInputCode(''); // 1. 清空输入框 UI
          fetchCaptcha(); // 2. 刷新验证码图片
          // 3. 通知父组件值已清空 (非常重要，否则 Form 表单里还保留着旧值)
          if (onCaptchaChange) {
            // 注意：这里传空字符串，但 uuid 暂时还需要保留当前的或者等 fetchCaptcha 更新
            // 由于 fetchCaptcha 是异步的，这里先传空值即可
            onCaptchaChange('', '');
          }
        },
      };
    }
  }, [actionRef, onCaptchaChange]); // 依赖项

  return (
    <div className={styles.captchaContainer}>
      {error && <div className={styles.error}>{error}</div>}

      <div className={styles.captchaWrapper}>
        {loading ? (
          <div className={styles.loading}>加载中...</div>
        ) : (
          <>
            <Input
              type="text"
              value={inputCode}
              onChange={handleInputChange}
              placeholder={placeholder}
              maxLength={4} // 根据你的验证码长度调整
              disabled={loading}
            />
            <img
              src={captchaImage}
              alt="验证码"
              className={styles.captchaImage}
              onClick={fetchCaptcha}
            />
          </>
        )}
      </div>
    </div>
  );
};

export default Captcha;
